package day_7_30;

public class Main3 {
    /**
     * 530. 二叉搜索树的最小绝对差
     * https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/?envType=study-plan-v2&envId=top-interview-150
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int ret = Integer.MAX_VALUE;
    private int pre = -0x3f3f3f3f; // 防止溢出

    public int getMinimumDifference(TreeNode root) {
        // 中序遍历之后是有序的，那么相邻的两个节点之间的差值最小就是返回值
        dfs(root);
        return ret;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        // 左 -> 根(处理最小值) -> 右
        dfs(root.left);
        ret = Math.min(ret,root.val - pre);
        pre = root.val;
        dfs(root.right);
    }
}
